package com.littlebee.storychild.ui;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.littlebee.storychild.R;
import com.littlebee.storychild.common.utils.DateUtils;
import com.littlebee.storychild.common.utils.GlideImageLoader;
import com.littlebee.storychild.common.utils.GsonUtils;
import com.littlebee.storychild.common.utils.NetWorkUtils;
import com.littlebee.storychild.common.utils.Utils;
import com.littlebee.storychild.ui.entry.Audiolist;
import com.littlebee.storychild.ui.entry.MyStoryEntry;
import com.littlebee.storychild.ui.entry.Playinfo;
import com.littlebee.storychild.ui.entry.StorysEntry;
import com.littlebee.storychild.ui.entry.User;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 故事详情
 */
public class PlayerStoryInfoActivity extends BaseActivity implements View.OnClickListener {


    Banner banner;
    private ListView gridView;
    MyStoryEntry myStoryEntry;
    List<String> urls = new ArrayList<String>();
    CommonAdapter<Audiolist> mAdapter;
    List<Audiolist> audiolists = new ArrayList<Audiolist>();
    List<Playinfo> infos = new ArrayList<Playinfo>();
    //private String fileName;
    private Handler handler = new Handler();
    StorysEntry storysEntry;


    /**
     * 播放or暂停
     */
    private ImageView playPauseIv;
    /**
     * 播放进度
     */
    private TextView nowProgressTv;
    /**
     * 播放进度条
     */
    private SeekBar progressBar;
    /**
     * 总进度
     */
    private TextView totalLengthTv;
    private  int index=0;
    List<String> titles = new ArrayList<String>();
    CommonToolbar toolbar;
    @Override
    public int getLayoutResId() {
        return R.layout.activity_player_story1_info;
    }

    @Override
    public void initView() {
        super.initView();

        banner = (Banner) findViewById(R.id.banner);
        gridView = (ListView) findViewById(R.id.listView);
        //infos = getIntent().getParcelableArrayListExtra("time");
        storysEntry = (StorysEntry) getIntent().getSerializableExtra("info");
        infos=storysEntry.getPlayinfos();
        playPauseIv = (ImageView) this.findViewById(R.id.play_pause_iv);
        nowProgressTv = (TextView) this.findViewById(R.id.now_progress_tv);
        progressBar = (SeekBar) this.findViewById(R.id.progressBar);
        totalLengthTv = (TextView) this.findViewById(R.id.total_length_tv);
        playPauseIv.setOnClickListener(this);
        progressBar.setOnSeekBarChangeListener(change);

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        getStoryInfo();

    }

    private void initChangeItem() {
        try {
            totalLengthTv.setText(DateUtils.getTimeString(getAmrDuration(storysEntry.getAudiomsgurl())));
        } catch (IOException e) {
            e.printStackTrace();
        }
        audiolists = myStoryEntry.getStorypages().get(0).getPagecaptionns();
        mAdapter = new CommonAdapter<Audiolist>(getActivity(), R.layout.layout_item_story_info1) {
            @Override
            protected void convert(ViewHolder viewHolder, Audiolist workerListEntry, int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                TextView name1 = viewHolder.findViewById(R.id.tv_1);
                name.setText(workerListEntry.getCaptiontxt());
                name1.setText((i + 1) + "");

            }
        };
        gridView.setAdapter(mAdapter);
        mAdapter.addAll(audiolists);
        for (int i = 0; i < myStoryEntry.getStorypages().size(); i++) {
            urls.add(myStoryEntry.getStorypages().get(i).getPageurl());
            titles.add("");

        }
        banner.setImages(urls)
                .setBannerTitles(titles)
                .setBannerStyle(BannerConfig.NOT_INDICATOR)
                .setImageLoader(new GlideImageLoader())
                .start();
    }

    /*
   * 拉取故事
   *
   * */
    public void getStoryInfo() {
        //phoneId=18611697983&storyid=1
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();
        hashMap.put("phoneId", user.getMobile());
        hashMap.put("storyid", storysEntry.getStoryid());
        NetWorkUtils.post(getActivity(), "getstoryinfo", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                String res = resObj.optString("response")/**.optString("storypages")*/;
                myStoryEntry = GsonUtils.getObjFromJSON(res, MyStoryEntry.class);
                toolbar.setTitle(myStoryEntry.getStoryname());
                initChangeItem();

            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);


            }
        });
    }


    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        toolbar = getToolbar();
        toolbar.setBgRes(R.color.trans);

        toolbar.setTitle("故事详情");


    }




    @Override
    protected void onPause() {
        super.onPause();
        mediaRelease();

    }
    //******************* 录音 ************************

    private MediaPlayer mPlayer = null;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突


    private void startPlayer(String item) {
        mPlayer = new MediaPlayer();
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaRelease();
                return true;
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaRelease();
                progressBar.setProgress(0);
                nowProgressTv.setText("00:00");
                playPauseIv.setImageResource(R.mipmap.player_big);
                index=0;
                mediaRelease();
                initChange(index);




            }
        });
        try {
            mPlayer.setDataSource(item);
            final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(false);
                mPlayer.prepare();
                mPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        progressBar.setMax(mPlayer.getDuration());
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (isChanging == true) {
                    return;
                }
                try {
                    if(mPlayer!=null) {
                        progressBar.setProgress(mPlayer.getCurrentPosition());
                    }

                }catch (IllegalStateException e){
                    e.printStackTrace();
                }catch (NullPointerException e){

                }
                handler.post(runnableUi);
            }
        };
        mTimer.schedule(mTimerTask, 0, 10);
    }

    private void initChange(int index) {
        banner.setChangeItem(index);
        audiolists = myStoryEntry.getStorypages().get(index).getPagecaptionns();
        LogUtils.i("XHX", "XHXSIe:" + audiolists.size());
        mAdapter.replaceAll(audiolists);
    }

    /**
     * 得到amr的时长
     *
     * @param file
     * @return amr文件时间长度
     * @throws IOException
     */
    public static int getAmrDuration(String file) throws IOException {
        int leng = 0;
        MediaPlayer player = new MediaPlayer();
        player.setDataSource(file);
        player.prepare();
        leng = player.getDuration();
        player.release();
        player = null;
        return leng;
    }

    private void mediaRelease() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    private SeekBar.OnSeekBarChangeListener change = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            isChanging = true;

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            mPlayer.seekTo(seekBar.getProgress());

            isChanging = false;
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.play_pause_iv:
                if (mPlayer != null) {
                    if (mPlayer.isPlaying()) {
                        playPauseIv.setImageResource(R.mipmap.player_big);
                        mPlayer.pause();
                    } else {
                        playPauseIv.setImageResource(R.mipmap.pause_big);
                        mPlayer.start();
                    }
                } else {
                    startPlayer(storysEntry.getAudiomsgurl());
                    playPauseIv.setImageResource(R.mipmap.pause_big);

                }
                break;
        }
    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面播放进度的文字标识
            try {
                if(mPlayer!=null&&mPlayer.isPlaying()) {
                    totalLengthTv.setText(DateUtils.getTimeString(mPlayer.getDuration()));

                    nowProgressTv.setText(DateUtils.getTimeString(mPlayer.getCurrentPosition()));
                    // TODO: 2017/9/11  判定图片是否相同
                    if(index==getIndex(mPlayer.getCurrentPosition())){
                        return;
                    }else{
                        index=getIndex(mPlayer.getCurrentPosition());
                        banner.setViewPagerIsScroll(false);
                        LogUtils.i("XHX","XHX下表："+index);
                        initChange(index);
                    }
                }
            }catch (IllegalStateException e){
                e.printStackTrace();
            }catch (NullPointerException e){
                e.printStackTrace();
            }


        }

    };
    private int getIndex(long time){
        for (int i=0;i<infos.size();i++){
            if(time<=(infos.get(i).getStartsecond())){
                return i;
            }
        }
        return 0;
    }

}
